package com.maker997.ajax.controller;

import com.maker997.ajax.dto.JsonResult;
import com.maker997.ajax.entity.City;
import com.maker997.ajax.entity.Province;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 级联菜单
 *
 * @author maker
 * @date 2017/11/13
 */
@Controller
@RequestMapping("/linkMenue")
public class LinkMenueController {

    /**
     * <option value='1'>四川</option> <option value='2'>山东</option>
     */
    @RequestMapping(value = "/htmlType",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String getProvince()
    {
        List<Province> list = Province.listAllProvice();
        StringBuilder sb = new StringBuilder(200);

        for (Province p:list)
        {
            sb.append("<option value='").append(p.getPid()).append("'>").append(p.getName()).append("</option> ");
        }
        return String.valueOf(sb);
    }

    @RequestMapping(value = "/city/{pid}",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String getCityByPid(@PathVariable("pid") Long pid)
    {
        System.out.println(pid);
        List<City> cities = City.listAllCity(pid);
        StringBuilder sb = new StringBuilder(300);

        for (City c:cities)
        {
            sb.append("<option value='").append(c.getCid()).append("'>").append(c.getName()).append("</option> ");
        }
        return String.valueOf(sb);
    }

    @RequestMapping(value = "/jsonType",method = RequestMethod.GET,produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public JsonResult<List<Province>> getAllProvince()
    {
        JsonResult result = null;
        try
        {
            List<Province> provinces = Province.listAllProvice();
            result = new JsonResult(true,provinces);

        }catch (Exception e)
        {
            result = new JsonResult(false,"系统错误");
        }
        return result;
    }

    @RequestMapping(value = "/jsonCity/{pid}",method = RequestMethod.GET,produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public JsonResult<List<City>> getJsonCityByPid(@PathVariable("pid") Long pid)
    {
        JsonResult result = null;
        try
        {
            List<City> cities = City.listAllCity(pid);
            result = new JsonResult(true,cities);
        }catch (Exception e)
        {
            result = new JsonResult(false,"系统错误");
        }
        return result;
    }
}
